<template>
  <div class="report-paper">
    <div class="content-wrapper" ref="content">
      <el-scrollbar v-if="!editable" class="report-scroll" ref="scrollView">
        <div class="report-conent">
          <div v-if="editContent" v-html-xss="editContent"></div>
        </div>
      </el-scrollbar>
      <tinymce-editor
        v-else-if="tinyMcHeight"
        class="editor-continer"
        v-model="editContent"
        :height="tinyMcHeight"
        use-in-report></tinymce-editor>
    </div>
  </div>
</template>

<script>
import TinymceEditor from '@com/TinymceEditor.vue'
import { debounce } from '@utility/utility'

export default {
  components: { TinymceEditor },
  props: {
    value: {
      type: String,
      default: '',
    },
    editable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      editContent: this.value,
      tinyMcHeight: 0,
      onWindowResize: null,
    }
  },
  watch: {
    value(val, oldVal) {
      this.editContent = val
      if (!oldVal && val) {
        if (this.editable) {
          this.resetTinyHeight()
        } else {
          this.$refs.scrollView && (this.$refs.scrollView.wrap.scrollTop = 0)
        }
      }
    },
    editContent(val) {
      console.log('this.editContent !== this.value..', this.editContent !== this.value, this.editContent !== val)
      if (this.editContent !== this.value) {
        this.$emit('change', val)
      }
      this.$emit('input', val)
    },
  },
  created() {
    this.onWindowResize = debounce(() => {
      this.resetTinyHeight()
    }, 200)
    window.addEventListener('resize', this.onWindowResize)
  },
  mounted() {
    this.editContent = this.value
    this.resetTinyHeight()
  },
  methods: {
    resetTinyHeight() {
      this.tinyMcHeight = 0
      this.$nextTick(() => {
        const clientHeight = this.$refs.content.clientHeight
        this.tinyMcHeight = (clientHeight && clientHeight - 20) || 500
      })
    },
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onWindowResize)
  },
}
</script>

<style lang="scss" scoped>
.report-paper {
  height: 100%;
  width: 100%;
  overflow-y: hidden;
  overflow-x: auto;
  .content-wrapper {
    padding: 10px 20px;
    // background: #f5f5f5;
    min-width: 22cm;
    height: 100%;
    overflow: hidden;
  }
  .report-scroll {
    margin: 0 auto;
    width: 21cm;
    height: 100%;
    background: #fff;
    box-shadow: 0px 0px 9px 0px rgba(0, 0, 0, 0.3);
    .report-conent {
      color: #333;
    }
  }
  .editor-continer {
    margin: 0 auto;
    width: 22cm;
    box-shadow: 0px 0px 9px 0px rgba(0, 0, 0, 0.3);
  }
}
</style>
